<template>
  <div
    class="page w-full h-full flex flex-col bg-F4F7FB"
    @touchstart="touchStart"
    @touchend="touchEnd"
  >
    <NavBar :title="title" :on-back="onPageBack">
      <template #custom>
        <slot name="navBarCustom"></slot>
      </template>
    </NavBar>
    <div class="flex-1 overflow-x-hidden">
      <slot name="content"></slot>
    </div>
  </div>
</template>

<script>
import NavBar from '@/components/nav-bar/index'

export default {
  components: {
    NavBar
  },
  props: {
    title: {
      type: String,
      default: ''
    },
    onPageBack: {
      type: [Function, undefined],
      default: undefined
    }
  },
  data() {
    return {
      // 刚触碰的时间
      startTime: 0,
      // 刚触碰的位置
      startPositionX: 0,
      startPositionY: 0,
      // 结束的位置
      endPositionX: 0,
      endPositionY: 0
    }
  },
  methods: {
    touchStart(event) {
      // 获取初始时间
      this.startTime = Date.now()
      // 获取初始的位置
      this.startPositionX = event.changedTouches[0].clientX
      this.startPositionY = event.changedTouches[0].clientY
    },
    touchEnd(event) {
      const endTime = Date.now()
      if (endTime - this.startTime > 2000) {
        // 如果手指滑动的距离超过2s 就默认不合法
        return
      }

      this.endPositionX = event.changedTouches[0].clientX
      this.endPositionY = event.changedTouches[0].clientY
      const xGap = Math.abs(this.endPositionX - this.startPositionX)
      const yGap = Math.abs(this.endPositionY - this.startPositionY)
      // 判断其滑动的距离是否值得触发
      let direction = ''
      if (xGap > yGap && xGap > 100) {
        direction = this.endPositionX - this.startPositionX > 0 ? 'right' : 'left'
      } else if (yGap > xGap && yGap > 100) {
        direction = this.endPositionY - this.startPositionY > 0 ? 'down' : 'up'
      } else {
        return
      }
      this.$emit('gesture', direction)
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  width: 100%;
  height: 100vh;

  .overflow-x-hidden {
    overflow-x: hidden;
  }
}
</style>
